import { app } from "../../scripts/app.js";

app.registerExtension({
    name: "Comfy.DynamicDirNode",
    async beforeRegisterNodeDef(nodeType, nodeData, app) {
        if (nodeData.name !== "DynamicDirNode") return;

        // 动态获取目录内容并生成端口
        nodeType.prototype.refreshOutputs = async function(dirPath) {
            const res = await fetch(`/api/list_dir?path=${encodeURIComponent(dirPath)}`);
            const data = await res.json();
            if (!data.success) {
                alert("目录读取失败: " + data.error);
                return;
            }
            const entries = data.entries;

            // 清除旧端口
            while (this.outputs.length > 0) {
                this.removeOutput(0);
            }

            // 端口与路径强绑定
            entries.forEach((entry, idx) => {
                this.addOutput(entry.name, "STRING");
                this.outputs[idx].entry = entry;
            });

            this.setDirtyCanvas(true, true);
        };

        // 每次参数变更时刷新端口
        nodeType.prototype.onPropertyChanged = function() {
            const dirPath = this.widgets_values?.[0] || "/";
            this.refreshOutputs(dirPath);
        };

        // 节点级监听端口连接/断开事件
        nodeType.prototype.onConnectionsChange = function(type, slot, connected, link_info, io_slot) {
            // type: 0=output, 1=input
            if (type === 0) { // 只处理输出端口
                const entry = this.outputs[slot]?.entry;
                if (entry) {
                    // 连接时
                    if (connected) {
                        fetch("/api/slot_connect", {
                            method: "POST",
                            headers: { "Content-Type": "application/json" },
                            body: JSON.stringify({
                                node_id: this.id,
                                slot: slot,
                                entry: entry,
                                event: "connect"
                            })
                        });
                    } else {
                        // 断开时
                        fetch("/api/slot_connect", {
                            method: "POST",
                            headers: { "Content-Type": "application/json" },
                            body: JSON.stringify({
                                node_id: this.id,
                                slot: slot,
                                entry: entry,
                                event: "disconnect"
                            })
                        });
                    }
                }
            }
        };

        // 每个端口只输出单个entry的路径
        nodeType.prototype.getOutputData = function(slot) {
            if (this.outputs && this.outputs[slot] && this.outputs[slot].entry) {
                return this.outputs[slot].entry.path;
            }
            return null;
        };
    }
}); 